package com.navinfo.collect.activity

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.widget.Button
import android.widget.EditText
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.navinfo.collect.R
import com.navinfo.collect.library.data.RealmUtils
import com.navinfo.collect.library.data.dao.impl.MapLifeDataBase
import com.navinfo.collect.library.data.entity.*
import com.navinfo.collect.library.map.NILayerManager
import com.navinfo.collect.library.system.Constant
import com.tencent.wcdb.room.db.WCDBOpenHelperFactory
import io.realm.Realm
import io.realm.RealmQuery
import io.realm.RealmResults
import io.realm.RealmSet
import org.json.JSONObject
import org.locationtech.jts.geom.Geometry
import org.locationtech.jts.io.WKTReader
import org.oscim.core.MercatorProjection
import java.io.File
import java.util.*

class PerformanceActivity : AppCompatActivity() {
    private val btnRealm: Button by lazy { findViewById(R.id.btn_realm) }
    private val btnSqlite: Button by lazy { findViewById(R.id.btn_sqlite) }
    private val btnWcdbSqlite: Button by lazy { findViewById(R.id.btn_wcdb_sqlite) }
    private val btnReadWcdb: Button by lazy { findViewById(R.id.btn_read_wcdb) }
    private val btnReadRealm: Button by lazy { findViewById(R.id.btn_read_realm) }
    private val btnDelWcdb: Button by lazy { findViewById(R.id.btn_del_wcdb) }
    private val btnDelRealm: Button by lazy { findViewById(R.id.btn_del_realm) }
    private val edtDuration: EditText by lazy { findViewById(R.id.edt_duration_time) }
    private val edtNum: EditText by lazy { findViewById(R.id.edt_num) }

    //private lateinit var db: SQLiteDatabase
    private lateinit var factory: WCDBOpenHelperFactory
    private lateinit var db: MapLifeDataBase
    private var lastNum: Int = 0
    private val TAG: String = "qj_PerformanceActivity"

    private val geo: String =
        "LINESTRING(116.26517061367645 40.06556950096703,116.27010859251465 40.06690798323373,116.27165156739875 40.067326890483,116.27267766066836 40.067633852714664,116.27318489354423 40.06778338976977)"
    private val geo2: String = "POINT(116.26517061367645 40.06556950096703)"
    private val calcNum: Int = 1000000
    private var lonArr = doubleArrayOf(112.26517061367645, 116.37165156739875, 115.27165156739875)
    private var latArr = doubleArrayOf(40.06556950096703, 41.06556950096703, 39.06556950096703)

    //private val geo2:String = geo;
    private var count: Int = 0;

    @RequiresApi(Build.VERSION_CODES.N)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_performance)
        init()

        btnRealm.setOnClickListener {
            // 启动线程，插入60W条数据
            realmInsert("0")
/*            Thread {
                Realm.getInstance(RealmUtils.getInstance().realmConfiguration).executeTransaction {
                    val vl = it.where(GeometryFeatureEntity::class.java).equalTo("name", "10000")
                        .findAll()
                    Log.e("PerformanceActivity", "查询结束")
                    vl.stream().forEach {
                        Log.d("PerformanceActivity", it.name)
                    }
                }
            }.start()*/
        }

        btnSqlite.setOnClickListener {
            // 启动线程，插入60W条数据
/*            object : Thread() {
                override fun run() {
                    val startTime: Long = System.currentTimeMillis()
                    db.beginTransaction()
                    try {
                        for (i in 1..600000) {
                            db.execSQL("insert into test (_id, name, age) values(" + i.toString() + "," + i.toString() + "," + i.toString() + ")")
                        }
                        db.setTransactionSuccessful()
                    } catch (e: Exception) {
                        Log.e("PerformanceActivity", e.toString())
                    } finally {
                        db.endTransaction()
                    }
                    val msg = Message()
                    msg.what = 0x101
                    msg.obj = System.currentTimeMillis() - startTime
                    handler.sendMessage(msg)
                }
            }.start()*/
/*            val cursor = db.query(
                "test",
                arrayOf("_id", "name", "age"),
                "_id<?",
                arrayOf("10000"),
                null,
                null,
                null
            )*/
            Log.e(TAG, "查询开始")
            val wkt =
                "POLYGON((121.772752 39.045522, 121.772743 39.045523,121.772693 39.045543, 121.77269 39.045545, 121.77263 39.045585,121.772627 39.045587, 121.772587 39.045627,121.772582 39.045637, 121.772572 39.045707,121.772573 39.045716, 121.772583 39.045746,121.772593 39.045776, 121.7726 39.045785, 121.77266 39.045825,121.772666 39.045827, 121.772706 39.045837,121.772708 39.045838, 121.772798 39.045848,121.772804 39.045848, 121.772894 39.045828,121.772901 39.045824, 121.772941 39.045794,121.772944 39.045791, 121.772974 39.045751,121.772978 39.04574, 121.772978 39.04568, 121.772977 39.045674, 121.772967 39.045644, 121.772965 39.045641, 121.772935 39.045591, 121.77293 39.045585, 121.77287 39.045545,121.772864 39.045543, 121.772824 39.045533,121.772823 39.045532, 121.772752 39.045522))"
            val sql =
                "select * from edit_tips where t_status=0 and rowid in (select rowid from SpatialIndex s where s.f_table_name='edit_tips' and s.search_frame=GeomFromText('POLYGON((121.772752 39.045522, 121.772743 39.045523,121.772693 39.045543, 121.77269 39.045545, 121.77263 39.045585,121.772627 39.045587, 121.772587 39.045627,121.772582 39.045637, 121.772572 39.045707,121.772573 39.045716, 121.772583 39.045746,121.772593 39.045776, 121.7726 39.045785, 121.77266 39.045825,121.772666 39.045827, 121.772706 39.045837,121.772708 39.045838, 121.772798 39.045848,121.772804 39.045848, 121.772894 39.045828,121.772901 39.045824, 121.772941 39.045794,121.772944 39.045791, 121.772974 39.045751,121.772978 39.04574, 121.772978 39.04568, 121.772977 39.045674,121.772967 39.045644, 121.772965 39.045641,121.772935 39.045591, 121.77293 39.045585, 121.77287 39.045545,121.772864 39.045543, 121.772824 39.045533,121.772823 39.045532, 121.772752 39.045522))')) and ST_Intersects(g_location, GeomFromText('POLYGON((121.772752 39.045522, 121.772743 39.045523,121.772693 39.045543, 121.77269 39.045545, 121.77263 39.045585,121.772627 39.045587, 121.772587 39.045627,121.772582 39.045637, 121.772572 39.045707,121.772573 39.045716, 121.772583 39.045746,121.772593 39.045776, 121.7726 39.045785, 121.77266 39.045825,121.772666 39.045827, 121.772706 39.045837,121.772708 39.045838, 121.772798 39.045848,121.772804 39.045848, 121.772894 39.045828,121.772901 39.045824, 121.772941 39.045794,121.772944 39.045791, 121.772974 39.045751,121.772978 39.04574, 121.772978 39.04568, 121.772977 39.045674, 121.772967 39.045644, 121.772965 39.045641, 121.772935 39.045591, 121.77293 39.045585, 121.77287 39.045545,121.772864 39.045543, 121.772824 39.045533,121.772823 39.045532, 121.772752 39.045522))'))"
            val sql1 = "select * from edit_tips where t_status=0"
            //val sql = "SELECT * FROM edit_pois where display_text=?"

            Log.e(TAG, "查询结束")
        }

        btnWcdbSqlite.setOnClickListener {
            object : Thread() {
                override fun run() {
                    wcdbImportInsert()
                    //wcdbInsert("test")
                }
            }.start()
        }

        btnReadRealm.setOnClickListener {

            object : Thread() {
                override fun run() {
                    realmRead("1", 20000)
                }
            }.start()

            object : Thread() {
                override fun run() {
                    realmInsert("1")
                }
            }.start()

            object : Thread() {
                override fun run() {
                    delRealm("1")
                }
            }.start()
            object : Thread() {
                override fun run() {
                    realmInsert("2")
                }
            }.start()
            object : Thread() {
                override fun run() {
                    realmRead("2", 20000)
                }
            }.start()
            object : Thread() {
                override fun run() {
                    delRealm("2")
                }
            }.start()
        }

        btnReadWcdb.setOnClickListener {

            object : Thread() {
                override fun run() {
                    wcdbReal("1", 200000)
                }
            }.start()
            object : Thread() {
                override fun run() {
                    // wcdbInsert("1")
                }
            }.start()
            object : Thread() {
                override fun run() {
                    //delWcdb("1")
                }
            }.start()
            object : Thread() {
                override fun run() {
                    // wcdbInsert("2")
                }
            }.start()
            object : Thread() {
                override fun run() {
                    wcdbReal("2", 200000)
                }
            }.start()

            object : Thread() {
                override fun run() {
                    //delWcdb("2")
                }
            }.start()
        }

        btnDelRealm.setOnClickListener {
            object : Thread() {
                override fun run() {
                    delRealm("0")
                }
            }.start()
        }


        btnDelWcdb.setOnClickListener {
            object : Thread() {
                override fun run() {
                    delWcdb("0")
                }
            }.start()
        }

    }

    fun init() {

        RealmUtils.getInstance().init(this@PerformanceActivity, Constant.ROOT_PATH, "realmTest")

        db = MapLifeDataBase.getDatabase(
            this@PerformanceActivity,
            NILayerManager.defaultDir + "/coremap.db"
        )
    }

    fun realmInsert(title: String) {
        Log.e(TAG, "realm=$title=新增开始")
        try {
            val startTime: Long = System.currentTimeMillis()

            //Thread.sleep(5000)

            Log.e(TAG, "realm=$title=新增beginTransaction")

            Realm.getInstance(RealmUtils.getInstance().realmConfiguration).beginTransaction()

            Log.e(TAG, "realm=$title=新增结束beginTransaction")

            Thread.sleep(10000)

            val txt = edtNum.text.toString()

            val num: Int = txt.toInt()

            for (i in 0..num) {
                if (i % 2 == 0) {
                    val entity: GeometryFeatureEntity = GeometryFeatureEntity(
                        UUID.randomUUID().toString() + i.toString(),
                        geo,
                        116.123555,
                        111.66633,
                        34.324555,
                        34.555555
                    )
                    Realm.getInstance(RealmUtils.getInstance().realmConfiguration).insert(entity)
                } else {
                    val entity: GeometryFeatureEntity = GeometryFeatureEntity(
                        UUID.randomUUID().toString() + i.toString(),
                        geo2,
                        116.123555,
                        111.66633,
                        34.324555,
                        34.555555
                    )
                    Realm.getInstance(RealmUtils.getInstance().realmConfiguration).insert(entity)
                }
            }

            Log.e(TAG, "realm=$title=新增commitTransaction")

            Realm.getInstance(RealmUtils.getInstance().realmConfiguration).commitTransaction()
            Log.e(TAG, "realm=$title=新增结束commitTransaction")

            lastNum = num

            Log.e(
                TAG,
                "realm==$title==fileSize==" + RealmUtils.getInstance().fileSize / 1024 / 1024
            )

            Log.e(TAG, "realm=$title=新增结束")

            val msg = Message()
            msg.what = 0x101
            msg.obj = "realm新增" + (System.currentTimeMillis() - startTime)
            handler.sendMessage(msg)
        } catch (e: Exception) {
            Log.e(TAG, "realm==$title==新增异常" + e.toString())
        } finally {
            Log.e(TAG, "realm==$title=新增=finally结束")
        }

    }

    fun realmRead(title: String, size: Int) {
        val startTime: Long = System.currentTimeMillis()

        try {
            val txt = edtNum.text.toString()
            val num: Int = txt.toInt()
            Log.e(TAG, "realm=$title=查询开始")

            val realmQuery: RealmQuery<GeometryFeatureEntity>? =
                Realm.getInstance(RealmUtils.getInstance().realmConfiguration).where(
                    GeometryFeatureEntity::class.java
                ).rawPredicate("ymin=34.555555 limit(" + (/*num+*/size) + ")")

            Log.e(TAG, "realm=$title=查询结束")

            val listResult: List<GeometryFeatureEntity>? = realmQuery?.distinct("id")?.findAll()

            val startTime1: Long = System.currentTimeMillis()

            //Thread.sleep(5000)

/*            Realm.getInstance(RealmUtils.getInstance().realmConfiguration).beginTransaction()

            listResult?.forEach {
                count += 1
                //Log.e("qj",count.toString())
                Realm.getInstance(RealmUtils.getInstance().realmConfiguration).insertOrUpdate(it)
            }

            Realm.getInstance(RealmUtils.getInstance().realmConfiguration).commitTransaction()
            Realm.getInstance(RealmUtils.getInstance().realmConfiguration)*/

            val msg1 = Message()
            msg1.what = 0x101
            msg1.obj = "realm查询" + (System.currentTimeMillis() - startTime1)
            handler.sendMessage(msg1)

            Log.e(TAG, "realm=$title=查询结束" + listResult?.size)
        } catch (e: Exception) {
            Log.e(TAG, "realm==查询异常" + e.toString())
        } finally {
            Log.e(TAG, "realm==finally查询结束")
        }
    }

    fun delRealm(title: String) {

        Log.e(TAG, "realm=$title=删除开始")

        val startTime: Long = System.currentTimeMillis()

        try {
            val txt = edtNum.text.toString()
            val num: Int = txt.toInt()

            Log.e(TAG, "realm=$title=删除开始where")

            val realmQuery: RealmQuery<GeometryFeatureEntity>? =
                Realm.getInstance(RealmUtils.getInstance().realmConfiguration).where(
                    GeometryFeatureEntity::class.java
                ).rawPredicate("ymin=34.555555 limit(" + (num + 1000) + ")")

            Log.e(TAG, "realm=$title=删除结束where")


            val listResult: RealmResults<GeometryFeatureEntity>? =
                realmQuery?.distinct("id")?.findAll()

            //Thread.sleep(3000)

            Log.e(TAG, "realm=$title=删除开始beginTransaction")

            Realm.getInstance(RealmUtils.getInstance().realmConfiguration).beginTransaction()

            Log.e(TAG, "realm=$title=删除结束beginTransaction")

            val reslut: Boolean? = listResult?.deleteAllFromRealm();

            Log.e(TAG, "realm=$title=删除commitTransaction")
            Realm.getInstance(RealmUtils.getInstance().realmConfiguration).commitTransaction()

            Log.e(TAG, "realm=$title=删除结束commitTransaction")

            Log.e(TAG, "realm=$title=删除" + reslut)
        } catch (e: Exception) {
            Log.e(TAG, "realm=$title=删除异常" + e.toString())
        } finally {
            Log.e(TAG, "realm=$title=finally=删除")
        }
        val msg = Message()
        msg.what = 0x101
        msg.obj = System.currentTimeMillis() - startTime
        handler.sendMessage(msg)
    }

    fun wcdbReal(title: String, size: Int) {

        val startTime: Long = System.currentTimeMillis()

        Log.e(TAG, "wcdb=$title=查询开始")

        try {
            val txt = edtNum.text.toString()
            val num: Int = txt.toInt()

            //Thread.sleep(2000)

            //val pois: Array<DataPoiFull?> = db.dataPoiDao.findAll(0,/*num+*/size)
            //val list:List<DataPoiFull>? = db.dataPoiDao.findYminList(42.11f,num)
            //val reslut:Array<String>? = db.dataPoiDao.find(num+10000,0,num)
            //Log.e(TAG,"wcdb=$title=查询结束"+pois?.size)

/*                        val msg = Message()
                        msg.what = 0x101
                        msg.obj = System.currentTimeMillis() - startTime
                        handler.sendMessage(msg)*/

            val startTimeUpdate: Long = System.currentTimeMillis()

            //val reslut:Int = db.dataPoiDao.update(pois)

            //Log.e(TAG,"wcdb=$title=更新结束"+reslut)

            val msg1 = Message()
            msg1.what = 0x101
            msg1.obj = "wcdb查询" + (System.currentTimeMillis() - startTimeUpdate)
            handler.sendMessage(msg1)

        } catch (e: Exception) {
            Log.e(TAG, "wcdb=$title=查询异常" + e.toString())
        } finally {
            Log.e(TAG, "wcdb=$title=finally查询")
        }
    }

    fun wcdbImportInsert() {

        val startTime: Long = System.currentTimeMillis()

        val fileName = Constant.ROOT_PATH + "/poi.txt"
        val project: Project = Project()
        project.createTime = System.currentTimeMillis().toString()
        val randoms = (0..1000).random() / 100f
        project.name = "test" + randoms
        db.projectManagerDao.insert(project)

        val layer1: LayerManager = LayerManager()
        layer1.projectId = project.id
        layer1.layerName = project.name
        layer1.geometryType = 0
        db.layerManagerDao.insert(layer1)

        val lines: List<String> = File(fileName).readLines()

        val elements = ArrayList<Element>()

        val count: Int = 0

        val list = ArrayList<TileElement>()

        val numCount: Int = lines.size

        lines.forEach { it ->

            val jobj: JSONObject = JSONObject(it)


            if (jobj != null && jobj.has("geometry")) {

                val element = Element()

                element.layerId = layer1.id


                if (this.count % 10 == 0) {
                    element.visibility = 1
                }

                element.geometry = jobj.getString("geometry")

                val reader = WKTReader()

                val geometry: Geometry?

                try {
                    geometry = reader.read(element.geometry)
                    if (geometry != null) {
                        val tileX = RealmSet<Int>()
                        getTileXByGeometry(geometry, tileX)
                        val tileY = RealmSet<Int>()
                        getTileYByGeometry(geometry, tileY)

                        //遍历存储tile对应的x与y的值
                        tileX.forEach { x ->

                            tileY.forEach { y ->
                                val tile = TileElement();
                                tile.elementId = element.id
                                tile.tilex = x
                                tile.tiley = y
                                list.add(tile)
                            }

                        }

                    }
                    val jsonArray = jobj.getJSONArray("names")
                    if (jsonArray != null) {
                        for (i in 0 until jsonArray.length()) {
                            val jobjTemp = jsonArray.getJSONObject(i)
                            if (jobjTemp != null && jobjTemp.optInt("class") == 1) {
                                element.displayText = jobjTemp.optString("name", "无名称")
                            }
                        }
                    }
                } catch (e: java.lang.Exception) {
                    // TODO Auto-generated catch block
                    e.printStackTrace()
                }


                elements.add(element)

                if (this.count % 5000 == 0) {
                    val msg = Message()
                    msg.what = 0x101
                    msg.obj = "wcdb新增$numCount" + "当前==" + this.count
                    handler.sendMessage(msg)
                    db.elementDao.insertList(elements)
                    db.tileElementDao.insertList(list)
                    elements.clear()
                    list.clear()
                }
            }

            this.count += 1

        }

        db.elementDao.insertList(elements)

        db.tileElementDao.insertList(list)

        val msg = Message()
        msg.what = 0x101
        msg.obj = "wcdb新增完成" + (System.currentTimeMillis() - startTime)
        handler.sendMessage(msg)

        Log.e(TAG, "wcdb===新增完成")

    }

    /**
     * 根据给定的geometry计算其横跨的20级瓦片X值
     */
    private fun getTileXByGeometry(geometry: Geometry?, tileXSet: MutableSet<Int?>): Set<Int?>? {
        var tileXSet: MutableSet<Int?>? = tileXSet
        val startTime = System.currentTimeMillis()
        if (tileXSet == null) {
            tileXSet = RealmSet()
        }
        if (geometry != null) {
            val envelope = geometry.envelope
            if (envelope != null) {
                val coordinates = envelope.coordinates
                // 最小最大x轴坐标，索引0位最小x值，索引1位最大x值
                if (coordinates != null && coordinates.size > 0) {
                    val minMaxX = doubleArrayOf(coordinates[0].x, coordinates[0].x)
                    for (coordinate in coordinates) {
                        // 获取最大和最小x的值
                        if (coordinate.x < minMaxX[0]) {
                            minMaxX[0] = coordinate.x
                        }
                        if (coordinate.x > minMaxX[1]) {
                            minMaxX[1] = coordinate.x
                        }
                    }
                    // 分别计算最大和最小x值对应的tile号
                    val tileX0 = MercatorProjection.longitudeToTileX(minMaxX[0], 20.toByte())
                    val tileX1 = MercatorProjection.longitudeToTileX(minMaxX[1], 20.toByte())
                    val minTileX = if (tileX0 <= tileX1) tileX0 else tileX1
                    val maxTileX = if (tileX0 <= tileX1) tileX1 else tileX0
                    println("getTileXByGeometry$envelope$minTileX===$maxTileX")
                    for (i in minTileX..maxTileX) {
                        tileXSet.add(i)
                    }
                }
            }
        }
        println("XGeometry-time:" + (System.currentTimeMillis() - startTime))
        return tileXSet
    }

    /**
     * 根据给定的geometry计算其横跨的20级瓦片Y值
     */
    private fun getTileYByGeometry(geometry: Geometry, tileYSet: MutableSet<Int?>): Set<Int?>? {
        var tileYSet: MutableSet<Int?>? = tileYSet
        val startTime = System.currentTimeMillis()
        if (tileYSet == null) {
            tileYSet = RealmSet()
        }
        val envelope = geometry.envelope
        if (envelope != null) {
            val coordinates = envelope.coordinates
            // 最小最大x轴坐标，索引0位最小x值，索引1位最大y值
            if (coordinates != null && coordinates.size > 0) {
                val minMaxY = doubleArrayOf(coordinates[0].y, coordinates[0].y)
                for (coordinate in coordinates) {
                    // 获取最大和最小y的值
                    if (coordinate.y < minMaxY[0]) {
                        minMaxY[0] = coordinate.y
                    }
                    if (coordinate.y > minMaxY[1]) {
                        minMaxY[1] = coordinate.y
                    }
                }
                // 分别计算最大和最小x值对应的tile号
                val tileY0 = MercatorProjection.latitudeToTileY(minMaxY[0], 20.toByte())
                val tileY1 = MercatorProjection.latitudeToTileY(minMaxY[1], 20.toByte())
                val minTileY = if (tileY0 <= tileY1) tileY0 else tileY1
                val maxTileY = if (tileY0 <= tileY1) tileY1 else tileY0
                println("getTileYByGeometry$envelope===$minTileY===$maxTileY")

                for (i in minTileY..maxTileY) {
                    tileYSet.add(i)
                }
            }
        }
        println("YGeometry-time:" + (System.currentTimeMillis() - startTime))
        return tileYSet
    }


    fun wcdbInsert(title: String) {

        Log.e(TAG, "wcdb==$title==新增开始")

        val startTime: Long = System.currentTimeMillis()

        try {
            val txt = edtNum.text.toString()

            val num: Int = txt.toInt()

            val elements: Array<Element?> = Array<Element?>(num, { Element() })
            val project: Project = Project()
            project.createTime = System.currentTimeMillis().toString()
            val randoms = (0..1000).random() / 100f
            project.name = title + randoms
            db.projectManagerDao.insert(project)

            val layer1: LayerManager = LayerManager()
            layer1.projectId = project.id
            layer1.layerName = project.name
            layer1.geometryType = 0
            db.layerManagerDao.insert(layer1)

            val layer2: LayerManager = LayerManager()
            layer2.projectId = project.id
            layer2.layerName = project.name + "2"
            layer1.geometryType = 0
            db.layerManagerDao.insert(layer2)


            // Start the app with a clean database every time.
            // Not needed if you only populate on creation.
            //mDao.deleteAll();
            val list = ArrayList<TileElement>()

            for (i in 0 until num) {

                val randoms1 = (0..1000).random() / 100f

                var randomsx: Float = (0..500).random() / randoms1
                if (randomsx > 20) {
                    randomsx /= 300f
                }
                var randomsy: Float = (0..500).random() / randoms1

                if (randomsy > 20) {
                    randomsy /= 300f
                }

                val geoX: Double = lonArr[i % lonArr.size] + randomsx
                val geoY: Double = latArr[i % latArr.size] + randomsy

                Log.e(TAG, "wcdb==$geoX==$randomsy====$randomsx")

                val element = Element()
                if (i % 2 == 0) {
                    element.layerId = layer1.id
                } else {
                    element.layerId = layer2.id
                }

                if (i % 10 == 0) {
                    element.visibility = 1
                }

                /*if(i%2==0) {
                    element.geometry = geo
                }else{
                    element.geometry = geo2
                }*/
                element.geometry = "POINT($geoX $geoY)"

                element.displayText = element.layerId.substring(0, 4) + "名称" + i
/*                element.maxx = (geoX * calcNum).toFloat()
                element.minx = (geoX * calcNum).toFloat()
                element.miny = (geoY * calcNum).toFloat()
                element.maxy = (geoY * calcNum).toFloat()*/
                elements[i] = element

                val tileId: Long = getTileId(10, geoX, geoY)
                val tile = TileElement();
                tile.elementId = element.id
                tile.tilex = tileId.toInt()
                list.add(tile)
            }

            db.elementDao.inserts(elements)

            db.tileElementDao.insertList(list)

            //Log.e(TAG, "wcdb==$title==新增数量"+pois.size)
        } catch (e: Exception) {
            Log.e(TAG, e.toString())
        } finally {
            Log.e(TAG, "wcdb==$title==新增finally")
        }

        val msg = Message()
        msg.what = 0x101
        msg.obj = "wcdb新增" + (System.currentTimeMillis() - startTime)
        handler.sendMessage(msg)

        Thread.sleep(10000)
        var file = File(NILayerManager.defaultDir + "/coremap.db")
        if (file.exists() && file.isFile) {
            Log.e(TAG, "wcdb==$title==fileSize==" + file.length() / 1024 / 1024)
        }
    }

    /**
     * 根据经纬度坐标计算 dns瓦片号
     *
     * @param nLevel dns瓦片的级别
     * @param x      精度坐标
     * @param y      纬度坐标
     * @return 瓦片号
     */
    fun getTileId(nLevel: Long, x: Double, y: Double): Long {
        var nTileID: Long
        var p: Int
        val nX = (x / 90 * (1 shl 30)).toInt()
        val nY = (y / 90 * (1 shl 30)).toInt()
        nTileID = if (nX < 0) 1 else 0.toLong()
        p = 30
        while (p > 30 - nLevel) {
            nTileID = nTileID shl 1
            if (nY and (1 shl p) != 0) {
                nTileID = nTileID or 1
            }
            nTileID = nTileID shl 1
            if (nX and (1 shl p) != 0) {
                nTileID = nTileID or 1
            }
            p--
        }
        nTileID += (1 shl (16 + nLevel).toInt()).toLong()
        return nTileID
    }

    fun delWcdb(title: String) {

        Log.e(TAG, "wcdb=$title=删除开始")

        val startTime: Long = System.currentTimeMillis()

        try {
            val txt = edtNum.text.toString()
            val num: Int = txt.toInt()

            //db.dataPoiDao.deleteAll()

            Log.e(TAG, "wcdb=$title=删除结束")

        } catch (e: Exception) {
            Log.e(TAG, "wcdb=$title=查询异常" + e.toString())
        } finally {
            Log.e(TAG, "wcdb=$title=finally=删除")
        }

        val msg = Message()
        msg.what = 0x101
        msg.obj = System.currentTimeMillis() - startTime
        handler.sendMessage(msg)
    }

    private val handler: Handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                0x101 -> edtDuration.setText(msg.obj.toString())
            }
        }
    }
}